<!DOCTYPE html>
<html>
   <head>
      <meta charset="utf-8">
      <meta name="viewport"
         content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
      <title>授权登陆页</title>
      <script src="./js/jquery.js"></script>

      <script>
         //适配兼容
         (function(doc, win) {
            console.log(doc, win)
            // var docEle = doc.documentElement;
            const dpr = Math.min(win.devicePixelRatio, 3),
               scale = 1 / dpr,
               resizeEvent = 'orientationchange' in window ? 'orientationchange' : 'resize';

            var recalCulate = function() {
               var docEle = document.documentElement,
                  w = docEle.clientWidth,
                  num = (w > 750 ? 750 : w) / 750; // **此时的750就是你设计稿的尺寸
               docEle.style.fontSize = (num * 100).toFixed(1) + 'px';
            };
            recalCulate();
            if (!doc.addEventListener) return;
            win.addEventListener(resizeEvent, recalCulate, false);
         })(document, window);
      </script>
   </head>
   <body>
      <img src="https://himg.bdimg.com/sys/portrait/item/public.1.1b043df2.Lwrisa5iuYshgxOXn45-wA.jpg" width="100" height="100" />
   </body>

   <script>
      var wxPay = false;
      var http;
      var APPID
      let debug = true; //调试模式
      let REDIRECT_URI = '';
      // if (debug) {
         APPID = 'wx9ca8f216ea2719b9';//m15
         http = window.location.protocol +'//' + window.location.host; //测试
         REDIRECT_URI = http + '/official_app/index.html';
      // } else {
      //    APPID = 'wx3bb3f2b60787b6d6';//唯巴蜀
      //    http = window.location.protocol +'//' + window.location.host; //测试
      //    REDIRECT_URI = http + '/broadcast/index.html?id=' + getQueryVariable('id');
      // }

      var api = {
         'login': http + '/wechat/official/login'
      }

      // 缓存有效期
      const foowwLocalStorage = {
         set: function(key, value, ttl_ms) {
            var data = {
               value: value,
               expirse: new Date(ttl_ms).getTime()
            };
            localStorage.setItem(key, JSON.stringify(data));
         },
         get: function(key) {
            var data = JSON.parse(localStorage.getItem(key));
            if (data !== null) {
               if (data.expirse != null && data.expirse < new Date().getTime()) {
                  localStorage.removeItem(key);
               } else {
                  return data.value;
               }
            }
            return null;
         },
         delete: function(key) {
            localStorage.removeItem(key);
         }
      }

      let SCOPE = 'snsapi_userinfo';
      var url = encodeURIComponent(window.location
         .href); //分享成功之后再次分享，微信会再url附带额外参数造成二次分享签名错误，这里处理下避免config：invalid signature签名失效
      console.log(url);
      var id = getQueryVariable('id'); //直播间id
      var auth = '';
      var userInfo = foowwLocalStorage.get("userInfo") ? foowwLocalStorage.get("userInfo") : {};
      var token = foowwLocalStorage.get("token") ? foowwLocalStorage.get("token") : '';
      var Equipment = '';
      var price = "0.01";
      var code = getQueryVariable('code');
      var share = getQueryVariable('state') ? decodeURIComponent(getQueryVariable('state')) : '';
      var likeNumber = 0;
      var thumb = 0;
      var likeTimer = null;
      // 直播赋值
      var videoUrl = '';

      var imgIcon = '';
      var vrHref = '';
      var isShowContent = false; //是否显示过页面

      // $('.content').addClass('show');
      // $('.content_mask').addClass('show');

      login(); //调用登录方法


      function login() {
         if (!code) {
            foowwLocalStorage.delete("token");
            location.href =
               `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APPID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=${SCOPE}&state=${share}#wechat_redirect `
         } else {
            console.log('token', token);
            // 登录接口
            if (!token) {
               console.log('没有登录信息');
               $.ajax({
                  type: 'get',
                  headers: {
                     'platform-id': APPID,
                     'client': 'h5',
                     'client-type':'h5'
                  },
                  url: api.login + '?code=' + code,
                  success: (res) => {
                     var date = new Date().getTime();

                     var data = JSON.parse(res);
                  },
                  error: (err) => {
                     console.log('err', err);
                  }
               })
            } else {
               console.log('有登录信息', userInfo);
            }
         }
      }


      function payOrder() {
         console.log('支付');
         $.ajax({
            type: 'post',
            url: api.order + '?id=' + id,
            headers: {
               'authorization': token,
               'platform-id': APPID,
               'client': 'h5'
            },
            success: (res) => {

               data = JSON.parse(res).data;
               console.log('paydata', data);
               if (typeof WeixinJSBridge == "undefined") {
                  if (document.addEventListener) {
                     document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                  } else if (document.attachEvent) {
                     document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                     document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                  }
               } else {
                  onBridgeReady(data);
               }
            }
         })
      }
      $.ajax({
         type: "get",
         headers: {
            'platform-id': APPID,
            'client': 'h5'
         },
         url: http + "/offiaccount/official/share?url=" + url, //替换网址，xxx根据自己jssdk文件位置修改
         success: function(res) {

            let data = JSON.parse(res)
            console.log('share', data)
            wx.config({
               debug: debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印
               appId: data.appId,
               timestamp: data.timestamp,
               nonceStr: data.nonceStr,
               signature: data.signature,
               jsApiList: [
                  'updateAppMessageShareData',
                  'updateTimelineShareData'
               ],
               openTagList: ["wx-open-launch-weapp"]
            });

         },
         error: function(data) {
            // alert(JSON.stringify(data));
            //alert("连接失败！");
         }
      });
      // wx.ready(function() {
      //    var shareData = {
      //       title: '梦幻之夜·上海爱乐乐团交响音乐会现场直播',
      //       desc: '在初冬到来之际，我们邀请历史悠久，实力雄厚的中央民族乐团为大家带来两场音乐盛典，期待您的到来', //这里请特别注意是要去除html
      //       link: REDIRECT_URI,
      //       imgUrl: imgIcon,
      //       success() {
      //          console.log('分享成功');
      //          $('.share_mask').hide();
      //       }
      //    };

      //    wx.updateTimelineShareData(shareData);
      //    wx.updateAppMessageShareData(shareData);
      // });

      function onBridgeReady(obj) {
         WeixinJSBridge.invoke(
            'getBrandWCPayRequest', {
               "appId": obj.appId, //公众号ID，由商户传入
               "timeStamp": obj.timeStamp, //时间戳，自1970年以来的秒数
               "nonceStr": obj.nonceStr, //随机串
               "package": obj.package,
               "signType": obj.signType, //微信签名方式：
               "paySign": obj.sign //微信签名
            },
            function(res) {
               if (res.err_msg == "get_brand_wcpay_request:ok") {
                  // 使用以上方式判断前端返回,微信团队郑重提示：
                  //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                  wxpayOk();
               }
            });
      }

      function wxpayOk() {
         wxPay = true;
         $('.popup').removeClass('active');
         $('._box_mask').removeClass('show');
         $('.video_load').show();
         setTimeout(() => {
            $.ajax({
               type: 'post',
               url: api.info + '?id=' + id,
               headers: {
                  'authorization': token,
                  'platform-id': APPID,
                  'client': 'h5'
               },
               success: (res) => {
                  var data = JSON.parse(res);
                  if (data.data.status == 1) {
                     videoUrl = data.data.flv_url;
                     player.src(videoUrl); // url 播放地址
                     $('.video_load').hide();
                  } else if (data.data.status == 2) {
                     alert(data.data.pause_reason)
                  } else if (data.data.status == 3) {
                     alert(data.data.stop_reason)
                  }

               }
            })
         }, 2000)
      }

      function getQueryVariable(variable) {
         var query = window.location.search.substring(1);
         var vars = query.split("&");
         for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) {
               return pair[1];
            }
         }
         return (false);
      }

      $('.right_dz').click(function() {
         clearTimeout(likeTimer)
         likeNumber += 1;
         if (thumb < 10000) {
            thumb += 1;
            $('#likeNumber').text(thumb);
         }
         likeTimer = setTimeout(() => {
            console.log('发送收藏:', likeNumber);
            $.ajax({
               type: 'post',
               url: api.thumb + '?id=' + id + '&times=' + likeNumber,
               headers: {
                  'authorization': token,
                  'platform-id': APPID,
                  'client': 'h5'
               },
               success: (res) => {
                  console.log(res);
                  likeNumber = 0;
               }
            })
         }, 3000);
      })
      $('.right_fx').click(function() {
         $('.share_mask').show();
      })
      $('.share_mask').click(function() {
         $(this).hide();
      })
      $('._cont_close').click(function() {
         $('.popup').removeClass('active');
      })
      $('.pay').unbind().click(function() {
         payOrder()
      })
      $('._box_mask').click(function() {
         $('.popup').addClass('active');
      })
      $('#video_zb').click(function() {
         $('.content_mask').removeClass('show');
         if ($(this).text() == '付费直播') {
            if (videoUrl) {
               player.play();
               $('.video_play').hide();
            } else {
               $('.popup').addClass('active');
            }
         } else {
            player.play();
            $('.video_play').hide();
         }
      });
      $('#video_vr').click(function() {
         $('.content_mask').removeClass('show');
         window.location.href = vrHref;
      });
      $('.video_play').click(function() {
         player.play();
         $(this).hide();
      })
      $('.video_full').click(function() {
         player.requestFullscreen();
      })
      $('video').click(function() {
         console.log('player.isFullscreen()',player.isFullscreen())
         if(player.isFullscreen()){
            player.exitFullscreen();
         }
      })
      // 解决ios显示域名问题
      window.alert = function(name) {
         var iframe = document.createElement("IFRAME");
         iframe.style.display = "none";
         iframe.setAttribute("src", 'data:text/plain,');
         document.documentElement.appendChild(iframe);
         window.frames[0].window.alert(name);
         iframe.parentNode.removeChild(iframe);
      }
   </script>
</html>
